package com.compass.doctor.ui.home.fragment

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode
import com.amap.api.location.AMapLocationListener
import com.compass.doctor.base.BaseVBFragment
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.callback.OnLocationButtonCallBack
import com.compass.doctor.databinding.FragmentRoutineDrugBinding
import com.compass.doctor.dialog.LocationDialog
import com.compass.doctor.ui.home.MedicalCareCompleteOrderActivity
import com.compass.doctor.ui.home.MedicalCareOrderActivity
import com.compass.doctor.ui.home.adapter.CareImplementedAdapter
import com.compass.doctor.ui.home.viewmodel.MedicalCareViewModel
import com.compass.framework.R
import com.compass.framework.constant.REFRESH_CARE
import com.compass.framework.constant.REFRESH_RX
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.helper.CompassAppHelper
import com.compass.framework.model.MedicalCareOrder
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.getStringFromResource
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * Description： 医护上门/待执行
 * Date:2023/12/11 21:04
 */
class CareImplementedFragment : BaseVBFragment<FragmentRoutineDrugBinding>(), OnRefreshListener,
    OnLoadMoreListener {

    private lateinit var careOrder: MedicalCareOrder
    private var mPage = 1
    private val medicalCareViewModel: MedicalCareViewModel by viewModels()
    private lateinit var careImplementedAdapter: CareImplementedAdapter
    private var onCustomItemClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(position: Int, msgType: String?) {
            //暂时取消 后续需要放开即可
            val item=careImplementedAdapter.getItem(position)
            when (msgType) {
                "phone" -> {
                    CommonMessageDialog.Builder(requireActivity())
                        .setTitle(getStringFromResource(R.string.dialog_tips_title))
                        .setMessage("是否立即呼叫患者？确定后平台会立即呼叫患者，患者接通后会再次呼叫您，请您留意接听电话（电话为029开头）。")
                        .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

                        .setCancel(getString(com.compass.framework.R.string.default_cancel))
                        .setonCancelListener {
                            it?.dismiss()
                        }
                        .setonConfirmListener {
                            medicalCareViewModel.nurseCall(item?.id)
                            it?.dismiss()
                        }.create().show()
                }

                "message" -> {
                    showToast("message")
                }

                "dialog" -> {
                    val item = careImplementedAdapter.getItem(position)
                    distributeButton(item)
                }
            }
        }
    }

    //声明AMapLocationClientOption对象
    private lateinit var mLocationOption: AMapLocationClientOption

    //声明AMapLocationClient类对象
    private lateinit var mLocationClient: AMapLocationClient

    //声明定位回调监听器
    private var mLocationListener = AMapLocationListener { amapLocation ->
        LogUtil.e("位置信息===${amapLocation.toJson()}");
        amapLocation?.let {
            if (amapLocation.errorCode == 0) {

                LocationDialog.Builder(
                    requireActivity(),
                    amapLocation,
                    careOrder,
                    onLocationButtonCallBack
                ).show()
            }else{
                showToast("定位失败请检查手机定位功能")
            }
        }
        dismissLoading()
    }

    private val onLocationButtonCallBack = object : OnLocationButtonCallBack {
        override fun onButtonCallBack(id: String,status: String,lat: Double, lot: Double) {
            showLoading()
            //{"label":"出发","value":"3"},{"label":"到达","value":"4"},{"label":"完成","value":"5"}
            when(status){
                "3"->{
                    medicalCareViewModel.nurseDeparted(id, lat, lot)
                }
                "4"->{
                    medicalCareViewModel.nurseArrive(id, lat, lot)
                }
            }
        }
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        //是隐私权政策是否包含高德开平隐私权政策  true是包含
        //隐私权政策是否弹窗展示告知用户 true是展示
        AMapLocationClient.updatePrivacyShow(requireContext(), true, true)
        //隐私权政策是否取得用户同意  true是用户同意
        AMapLocationClient.updatePrivacyAgree(requireContext(), true)
        careImplementedAdapter = CareImplementedAdapter()
        careImplementedAdapter.setOnCustomItemClick(onCustomItemClick)
        careImplementedAdapter.onItemClickListener={_, position ->
            val item = careImplementedAdapter.getItem(position)
            item?.let {
                MedicalCareOrderActivity.start(requireContext(), item.id)
            }


        }
        mBinding?.refreshLayout?.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@CareImplementedFragment)
            setOnLoadMoreListener(this@CareImplementedFragment)
        }
        mBinding?.recyclerView?.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            adapter = careImplementedAdapter
        }
    }


    private fun distributeButton(careOrder: MedicalCareOrder?) {
        careOrder?.let {
            this.careOrder = it
            when (it.status) {
                "5" -> {
                    //完成订单
                    MedicalCareCompleteOrderActivity.start(requireContext(),careOrder.id,careOrder)
                }
                else -> {
                    locationIsGranted()
                }
            }
        }
    }

    override fun initData() {
        showLoading()
        getDataList()
        medicalCareViewModel.messageLiveData.observe(this) {
            dismissLoading()
            if (mPage == 1) {
                careImplementedAdapter.setData(it)
                mBinding?.refreshLayout?.finishRefresh()
                mBinding?.refreshLayout?.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding?.viewEmpty?.visible()
                } else {
                    mBinding?.viewEmpty?.gone()
                }
            } else {
                mBinding?.refreshLayout?.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    careImplementedAdapter.addAll(it)
                } else {
                    mBinding?.refreshLayout?.setEnableLoadMore(false)
                }
            }
        }
        medicalCareViewModel.departLiveData.observe(this) {
            dismissLoading()
            LiveDataBus.get().with(REFRESH_RX).postValue(REFRESH_RX)
            getDataList()
        }

        medicalCareViewModel.reachLiveData.observe(this) {
            dismissLoading()
            getDataList()
        }
        medicalCareViewModel.callLiveData.observe(this){
            if (it) showToast("正在为您呼叫患者，请稍后")

        }


        LiveDataBus.get().with(REFRESH_CARE, String::class.java).observe(this){
            getDataList()
        }

        LiveDataBus.get().with(REFRESH_RX, String::class.java).observe(this){
            getDataList()
        }
    }

    private fun getDataList() {

        medicalCareViewModel.getNurseList(mPage)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getDataList()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getDataList()
    }




    private fun initLocation() {
        //初始化定位
        mLocationClient = AMapLocationClient(CompassAppHelper.getApplication())
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener)
        //初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()
        //设置为签到模式（签到、出行、运动）
        mLocationOption.locationPurpose = AMapLocationClientOption.AMapLocationPurpose.SignIn
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.locationMode = AMapLocationMode.Hight_Accuracy;
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.isNeedAddress = true;
        //获取最近3s内精度最高的一次定位结果：
        mLocationOption.isOnceLocationLatest = true;
        mLocationClient.setLocationOption(mLocationOption);
        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        mLocationClient.stopLocation();
        mLocationClient.startLocation();
    }

    /**
     * 判断是否有定位权限
     */
    private fun locationIsGranted() {
        //判断是否有权限
        if (XXPermissions.isGranted(
                requireActivity(), Permission.ACCESS_FINE_LOCATION,
                Permission.ACCESS_COARSE_LOCATION
            )
        ) {
            showLocationDialog()
        } else {
            CommonMessageDialog.Builder(requireActivity())
                .setTitle(getStringFromResource(com.compass.doctor.R.string.permission_explain))
                .setMessage(getStringFromResource(com.compass.doctor.R.string.image_permission_location))
                .setConfirm(getStringFromResource(R.string.default_confirm))
                .setCancel(getString(R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    requestPermissions()
                    it?.dismiss()
                }.create().show()
        }
    }

    private fun showLocationDialog() {
        showLoading("正在定位请稍后...")
        initLocation()
    }


    /**
     * 请求权限
     */
    private fun requestPermissions() {
        XXPermissions.with(this)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        TipsToast.showTips("获取部分权限成功，但部分权限未正常授予")
                        return
                    }
                    showLocationDialog()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {

                        TipsToast.showTips("被永久拒绝授权，请手动授予相关权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(
                            this@CareImplementedFragment,
                            permissions
                        )
                    } else {
                        TipsToast.showTips(R.string.default_agree_permission)
                    }
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        if (this::mLocationClient.isInitialized){
            mLocationClient.stopLocation();
            mLocationClient.onDestroy()
        }

    }
}